package chalmers.game.subterranean.model.items;

import chalmers.game.subterranean.model.world.IWorld;
import chalmers.game.subterranean.model.world.squares.Square;
import chalmers.game.subterranean.model.world.squares.blocks.actionblocks.Teleport;
import chalmers.game.subterranean.util.Direction;
import chalmers.game.subterranean.util.Position;
import org.apache.log4j.Logger;

/**
 * User: Mikael Friederici Date: 2014-05-17 Time: 00:38
 */
public class TeleportItem implements IEquippableItem {
  IWorld world;
  private Position portA;
  private Position portB;
  private static final Logger logger = Logger.getLogger("subLog");
  public final String name = "Teleport";


  private Teleport blockA;
  private Teleport blockB;

  public TeleportItem(IWorld world) {
    this.world = world;
    portA = null;
    portB = null;
  }

  @Override
  public void action(Position position, Direction direction) {
    if (!isActive()) {
      connectPort(position);
    } else {
      logger.info("Error: Teleport have already been used!");
    }
  }

  public Position getOtherPort(Position port) {
    if (!isActive())
      return port;
    if (port.equals(portA))
      return portB;
    if (port.equals(portB))
      return portA;
    return port;
  }

  public boolean isActive() {
    if (portA != null && portB != null)
      return true;
    else
      return false;
  }

  public boolean connectPort(Position position) {
    if (portA == null) {
      portA = position;
      blockA = new Teleport(null);
      world.addActionBlock(position, new Square(blockA));
      return true;
    } else if (portB == null) {
      portB = position;
      blockB = new Teleport(portA);
      blockA.setOtherEnd(portB);
      world.addActionBlock(position, new Square(blockB));
      return true;
    } else {
      return false;
    }
  }

  @Override
  public String toString() {
    return name;
  }
}
